//
const express = require("express");
//引入body-parser
var bodyParser = require('body-parser');
//引入 mongoose 模块
const mongoose=  require('mongoose');
//连接数据库
mongoose.connect('mongodb://127.0.0.1:27017/shop');
//设置连接成功的回调
mongoose.connection.on('open', () => {
    //文档结构对象的创建
    const UserSchema = new mongoose.Schema({
        username: String,
        password: String
    });
    //创建模型对象
    const UserModel = mongoose.model('users', UserSchema);

    //
    const app = express();
    //设置body-parser的中间件
    app.use(bodyParser.urlencoded({ extended: false }))

    //设置 ejs 模板引擎
    app.set('view engine','ejs');
    app.set('views','./views');

    //路由
    //显示表单页面
    app.get('/register', (request, response) => {
        response.render('zhuce');
    });

    //注册用户
    app.post('/register', (request, response) => {
        //执行数据插入
        UserModel.create(request.body, (err, data) => {
            if(err){
                //注册失败
                response.send('注册失败, 请重试');
            }else{
                //注册成功
                response.send('恭喜您 注册成功!');
            }
        });
    });

    //
    app.listen(80, () => {
        console.log('服务已经启动. 80 端口监听中....');
    })

});